package engine.newUi
{
	import com.greensock.TweenLite;
	
	import engine.data.BindManage;
	import engine.data.ModelLocator;
	import engine.data.Record;
	import engine.event.CustomEvent;
	import engine.flag.PlayerActionFlag;
	import engine.flag.ResourcesPath;
	import engine.logic.login.PlayCDTimerLogic;
	import engine.logic.tips.TipsManage;
	import engine.net.datatype.WString;
	import engine.net.event.CustomMsgEvent;
	import engine.net.messages.CustomToClientFlag;
	import engine.net.messages.CustomToServerFlag;
	import engine.net.mgr.SystemSender;
	import engine.ui.AlertUI;
	import newx.utils.FilterUtil;
	
	import flash.display.MovieClip;
	import flash.display.SimpleButton;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.geom.Point;
	import flash.text.TextField;
	import flash.utils.Timer;
	
	import newx.com.config.StaticIni;
	import newx.com.control.NxClip;
	import newx.com.control.window.NxWindowEvent;
	import newx.com.loader.SwfLoader;

	public class JHtravelLogic
	{
		public static var _self:JHtravelLogic;
		
		private var _model:ModelLocator;
		
		private var _ui:JHtravelUI;
		
		private var _bind:BindManage;
		
		private var _bindIndex:int	=	-1;
		
		/**开始游历按钮*/
		private var beginMC:MovieClip;
		
		private var _infoArr:Array;
		
		/**cd计时器*/
		//private var _timer:Timer;
		
		/**游历总次数*/
		private var _travelAllCount:int	=	10;
	
		//
		private var _roleModel:MovieClip;
		
		/**"开始游历"按钮是否可以点击*/
		private var _isStop:Boolean	=	false;
		
		/**剩余游历次数*/
		private var _travelCount:int	=	0;
		
		/**人物游历宽度*/
		private  var runWidth:int		=	600;
		
		/**人物游历长度*/
		private var runHeight:int		=	300;
		
		/**判断人员是否齐全*/
		private var _typeCount:int		=	0;
		public static function getInstance():JHtravelLogic
		{
			if(_self == null)
			{
				_self	=	new JHtravelLogic();
			}
			return _self
		}
		public function JHtravelLogic()
		{
		}
		
		public function Init():void
		{
			_model		=	ModelLocator.getInstance();
			_bind		=	BindManage.getInstance();
			_infoArr	=	[];
			beginMC		=	ui.backMC.getChildByName("bt") as MovieClip;
			beginMC.buttonMode	=	true;
			beginMC.gotoAndStop(1);
			groupInit();
			//_timer		=	new Timer(1000);
			//_timer.addEventListener(TimerEvent.TIMER, timerHandle);
			PlayCDTimerLogic.getInstance().resgis(10,CDBackFun);
		}
		public function CDBackFun(val:int,col:int):void
		{
			if(val <= 0)
			{
				ui.timelab.htmlText	=	"";
				beginMC.gotoAndStop(1);
				_isStop	=	true;
				beginMC.mouseEnabled	=	true;
			}
			else
			{			
				ui.timelab.htmlText	=	PlayCDTimerLogic.getInstance().getTimerStr(val,false);
			}			
		}

		/**
		 * 初始化主角界面框 
		 * 
		 */		
		private function groupInit():void
		{
			var mc	:MovieClip		=	ui.backMC.getChildByName("mc_0") as MovieClip;
			var bt_1:SimpleButton	=	mc.getChildByName("bt_1") as SimpleButton;
			var bt_2:SimpleButton	=	mc.getChildByName("bt_2") as SimpleButton;
			var Txt_1:TextField		=	mc.getChildByName("Txt_1") as TextField;
			var Txt_2:TextField		=	mc.getChildByName("Txt_2") as TextField;
			var img:MovieClip		=	mc.getChildByName("img2") as MovieClip;
			var clip:NxClip			=	new NxClip();
			img.addChild(clip);
			clip.source		=	ResourcesPath.getMiniHeadPic(22011100);
			bt_1.visible	=	false;
			bt_2.visible	=	false;
			Txt_1.htmlText	=	"";
			Txt_2.htmlText	=	"";
		}
		
		/**
		 * 显示数据 
		 * @param arr
		 * 
		 */		
		public function addSwfHandle(arr:Array):void
		{
			var single:MovieClip;
			var leftBtn:SimpleButton;
			var rightBtn:SimpleButton;
			var clip:NxClip;
			var Txt_1:TextField	;
			var Txt_2:TextField	;
			var img:MovieClip;
			for(var i:int = 1;i < arr.length;i++)
			{
				single	=	ui.backMC.getChildByName("mc_"+i) as MovieClip;
				clip	=	new NxClip();
				clip.isCache	=	true;
				leftBtn	=	single.getChildByName("bt_1") as SimpleButton;
				rightBtn=	single.getChildByName("bt_2") as SimpleButton;
				Txt_1	=	single.getChildByName("Txt_1") as TextField;
				Txt_2	=	single.getChildByName("Txt_2") as TextField;
				img		=	single.getChildByName("img2") as MovieClip; 
				img.addChild(clip);
				Txt_1.mouseEnabled	=	false;
				Txt_2.mouseEnabled	=	false;
				single.addEventListener(MouseEvent.CLICK,onsingleClickHandle);
				single.addEventListener(MouseEvent.ROLL_OVER,onsingleOverHandle);
				single.addEventListener(MouseEvent.ROLL_OUT,onsingleOutHandle);
				single["data"]		=	i;
				if(arr[i][1] != "")
				{
					leftBtn.visible	 =	false;			
					rightBtn.visible =	false;
					Txt_1.visible	 = 	false;
					Txt_2.visible	 = 	false;
					img.visible		 = 	true;
					clip.source		=	ResourcesPath.getMiniHeadPic(22011100);
				}
				else
				{
					Txt_1.visible	 = 	true;
					Txt_2.visible	 = 	true;
					leftBtn.visible	 =	true;			
					rightBtn.visible =	true;
					img.visible		 = 	false;
					clip.clear();
				}
			}
	
		}
		
		/**
		 * 邀请好友和NPC点击事件 
		 * @param e
		 * 
		 */		
		private function onsingleClickHandle(e:MouseEvent):void
		{
			var name:String;
			var num:int	=	(e.currentTarget as MovieClip)["data"];
			if(e.target as SimpleButton)
			{
				name	=	(e.target as SimpleButton).name;
				switch(name)
				{				
					case "bt_1":
					{		
						EngageFriendLogic.getInstance().callForShow(0,callbackFun,null,num);
						return;				
						break;
					}		
					case "bt_2":
					{
						onClickrightHandle(num);
						break;
					}
					default:
					{
						break;
					}
				}
				return;
			}
		}
		
		/**
		 * 好友要求回调函数 
		 * @param 功能类型 ID
		 * @param  好友姓名 name
		 * @param  index
		 * 
		 */		
		public function callbackFun(ID:int,name:String,index:int):void
		{
			var friendName:WString	=	new WString(name);
			SystemSender.getInstance().CustomMsgEx(	
				CustomToServerFlag.CLIENT_CUSTOMMSG_WORLD_TRAVEL_INVITE,[index,friendName]);
		}
		/**
		 * 邀请NPC 
		 * @param 第几个邀请界面：imdex
		 * 
		 */		
		private function onClickrightHandle(imdex:int):void
		{
			var	title		:String			=	StaticIni.getSwfLangStr("31100");
			var descTitle	:String			=	StaticIni.getSwfLangStr("UIStr_1000486");
			var	iniDesc		:String			=	StaticIni.getSwfLangStr("UIStr_1000485");
			var	yesBtn		:String			=	StaticIni.getSwfLangStr("AlertEx_16");
			var	noBtn		:String			=	StaticIni.getSwfLangStr("AlertEx_1");
			var tipsStr:String	=	StaticIni.getSwfLangStrVar("Lobby8",[1000]);
			AlertUI.showAlertEx(title,tipsStr,[yesBtn,noBtn],AlertUI.YES|AlertUI.NO,createGuild);
			
			function createGuild( type:int, str:String, clickData:* ):void
			{
				if(AlertUI.YES == type )
				{
					SystemSender.getInstance().CustomMsgEx(	
						CustomToServerFlag.CLIENT_CUSTOMMSG_WORLD_TRAVEL_INVITE,[imdex]);
				}
			}
		}
		
		private function onsingleOverHandle(e:MouseEvent):void
		{
			TipsManage.showTips(StaticIni.getSwfLangStrVar("Lobby7",[1000]));
		}
		
		private function onsingleOutHandle(e:MouseEvent):void
		{
			TipsManage.hideTips();
		}
		
		public function BeforeShow():void
		{
			_model.addEventListener(
				String(CustomToClientFlag.SERVER_CUSTOMMSG_BEGIN_WORLD_TRAVEL),beginTravel);	
			_model.addEventListener(
				String(CustomToClientFlag.SERVER_CUSTOMMSG_WORLD_TRAVEL_INFO),infoTravel);
			_model.addEventListener(
				String(CustomToClientFlag.SERVER_CUSTOMMSG_WORLD_TRAVEL_Prize),prizeTravel);
			ui.closeBtn.addEventListener(MouseEvent.CLICK,onClickCloseHandle);
			beginMC.addEventListener(MouseEvent.CLICK,onBeginClickHandle);
			if(_bindIndex == -1)
			{
				_bindIndex	=	_bind.BindProp(_model.scene.Role,"WorldTravelCount",this,"travelCount");	
			}
			SystemSender.getInstance().CustomMsg(	
				CustomToServerFlag.CLIENT_CUSTOMMSG_SHOW_WORLD_TRAVEL_UI);
		}
		
		private function onBeginClickHandle(e:MouseEvent):void
		{		
			var frame:int		=	beginMC.currentFrame;			
			if(frame == 1)
			{		
				if(_isStop && _typeCount == 4)
				{
					if(_travelCount <= 0)
					{
						AlertUI.showAlert("","游历次数不够",AlertUI.OK);
						return;
					}				
					SystemSender.getInstance().CustomMsg(	
						CustomToServerFlag.CLIENT_CUSTOMMSG_WORLD_TRAVEL_BEGIN);
				}

			}
			if(frame == 2)
			{
				var str:String	=	StaticIni.getSwfLangStrVar("Lobby9",[1000]);
				AlertUI.showAlert("",str,AlertUI.YES|AlertUI.NO,function(type:int, str:String, clickData:*):void{
					if(type == AlertUI.YES)
					{
						SystemSender.getInstance().CustomMsgEx(
							CustomToServerFlag.CLEINT_CUSTOMMSG_REQUEST_CLEAR_CD,[10,1000]);
					}
				})
			}

		}
		
		/**
		 * 开始游历
		 * @param e
		 * 
		 */		
		private function beginTravel(e:CustomMsgEvent):void
		{
			loadModel();
			beginMC.filters		=	[FilterUtil.GrayColorFilter];
		}
		
		/**
		 * 游历江湖信息
		 * @param e
		 * 
		 */		
		private function infoTravel(e:CustomMsgEvent):void
		{
			var arr:Array		=	e.pList;
			_typeCount			=	0;
			_isStop				=	true;
			beginMC.filters		=	[];
			//beginMC.mouseChildren	=	true;
			for(var i:int = 0; i < arr.length;i+=2)
			{
				if(arr[i+1] == "")
				{
					beginMC.gotoAndStop(1);
					_isStop	=	false;
					beginMC.filters		=	[FilterUtil.GrayColorFilter];
					_infoArr[i/2]		=	[arr[i],arr[i+1]];
				}
				else
				{
					_typeCount++;
					_infoArr[i/2]	=	[arr[i],getpartnerID(arr[i+1])];
				}
			}
			addSwfHandle(_infoArr);
		}
		
		/**
		 * 根据伙伴的名字返回伙伴的头像ID 
		 * @param name
		 * 
		 */		
		private function getpartnerID(name:String):String
		{
			var friend:Record	= 	_model.scene.GetRecordEx("Friend");
			var	arr:Array		=	friend.recArr;
			for( var i:int = 0; i < arr.length;i++ )
			{
				for( var j:int = 0; j < (arr[i] as Array).length;j++ )
				{
					if(name == arr[i][j])
					{
						return arr[i][10]
					}
				}
			}
			return name;
		}
		/**
		 * 游历江湖结束
		 * @param e
		 * 
		 */		
		private function prizeTravel(e:CustomMsgEvent):void
		{
			TweenLite.killTweensOf(_roleModel);
			modelStop();
			beginMC.gotoAndStop(2);
			beginMC.mouseEnabled	=	false;
			beginMC.filters			=	[];	
		}
		
		/**
		 * 加载人物模型 
		 * 
		 */		
		private function loadModel():void
		{
			if(_roleModel==null)
			{
				var swfURL:String	=	ResourcesPath.getRoleModel(_model.scene.Role);
				SwfLoader.StartLoad(swfURL, null, loadOver);
				//"res/actors/role_22013100_6.swf"
			}
			else
			{
				//var po:Point	=	new Point(500,600);
				runToPoint(movieArea());
			}
		}
		private function loadOver(mc:MovieClip,pl:Array):void
		{
			if(mc)
			{
				mc.scaleX	=	mc.scaleY	=	0.3;
				_roleModel	=	mc;
				mc.x=mc.y=100;
				ui.addChild(_roleModel);
				modelStop();
			}
			else
			{
//				trace("Error~WorldMapLogic.loadOver(mc, pl)没人物模型");
				
			}
			//var po:Point	=	new Point(500,600);
			runToPoint(movieArea());
		}
		
		private function runToPoint(point:Point):void
		{
			if(point.x < _roleModel.x)
			{
				_roleModel.scaleX	=	-0.3;
			}
			else
			{
				_roleModel.scaleX	=	0.3;
			}
			modelRun();
			TweenLite.to(_roleModel,getDistance()/10,{x:point.x,y:point.y,onComplete:endRun});
			function getDistance():Number
			{
				var p:Point=new Point(_roleModel.x,_roleModel.y);
				return Point.distance(p,point);
			}
		}
		private function endRun():void
		{
			modelStop();
			if(!_isStop)
			{
				runToPoint(movieArea())
			}	
		}
			
		private function modelRun():void
		{
			_roleModel.gotoAndPlay(PlayerActionFlag.Run);
		}
		private function modelStop():void
		{
			_roleModel.gotoAndPlay(PlayerActionFlag.NormalWait);
		}
		
		/**
		 * 游历范围 
		 * @return 
		 * 
		 */		
		private function movieArea():Point
		{
			var xNum:int	=	200+Math.random() *runWidth;
			var yNum:int	=	300+Math.random() *runHeight;	
			var po:Point	=	new Point(xNum,yNum);
			return po
		}
		
		/**
		 *  游历次数
		 * @param val
		 * 
		 */		
		public function set travelCount(val:int):void
		{
			_travelCount	=	_travelAllCount-val;
			ui.travelLab.htmlText	=	StaticIni.getSwfLangStrVar("UIString_1000149",[_travelCount]);	
		}
		
		public function AfterHide():void
		{
			
		}
		
		private function onClickCloseHandle(e:MouseEvent):void
		{
			ui.hide();
		}
		
		public function get ui():JHtravelUI
		{
			if(_ui == null)
			{
				_ui	=	new JHtravelUI();
			}
			return _ui
		}
	}
}